<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\cache\driver\Redis;
class Menu extends Auth
{

    public $redis;

	public function __construct(Request $request){
        parent::__construct($request);
        $this->data = $request->param();
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->getChildIDdata = [];
    }


    // 侧边栏列表
    public function list(Request $request){
        // 按菜单名查找条件
        if(isset($this->data['searchText']) && $this->data['searchText']){
            $where['mu.content'] = ['like', '%' . trim($this->data['searchText']) . '%'];
            // $where['mu.content'] = ['like', '%部门%'];
            $returnData['searchText'] = $this->data['searchText'];
        }else{
            $returnData['searchText'] = '';
        }
        // 按控制器查找条件
        if(isset($this->data['control']) && $this->data['control']){
            $where['zu.control'] = trim($this->data['control']);
            $returnData['control'] = $this->data['control'];
        }else{
            $returnData['control'] = '';
        }
        $where['mu.lang'] = $this->lang;
        // vue获取数据，所以浏览器直接打开直接跳转页面由VUE获取数据遍历
        if($request->isAjax()){
            $menuList = getSearch('menu','zu',['zu.*,mu.content'],$where,[['multi_lang mu','zu.mkey = mu.mkey']],'zu.drank asc');
            // 按条件搜索时不用进行level比较
            if(count($where) == 1){
                $menuList = getTree($menuList);
            }

            foreach ($menuList as $k => $v) {
                if(count($where) > 1){
                    $menuList[$k]['level'] = 0;
                    $menuList[$k]['child'] = 0;
                }else{
                    $menuList[$k]['child'] = Db::name('menu')->where('pid',$v['id'])->count();
                }
                $menuList[$k]['is_menu'] = $menuList[$k]['is_menu'] == 1 ? 'O' : '-';
                $menuList[$k]['is_disable'] = $menuList[$k]['disable'] == 1 ?  'O' : '-';
                $menuList[$k]['control'] = $menuList[$k]['control'] != '' ?  $menuList[$k]['control'] : '-';
                $menuList[$k]['option'] = $menuList[$k]['option'] != '' ?  $menuList[$k]['option'] : '-';
                $menuList[$k]['style'] = $menuList[$k]['style'] != '' ?  $menuList[$k]['style'] : '-';
            }
            // 获取分页数据
            $returnData['size'] = count( $menuList);
            if(isset($this->data['page']) && isset($this->data['limit'])){
                if($this->data['limit']*($this->data['page']-1) < $returnData['size']){
                    $menuList = array_slice($menuList,$this->data['limit']*($this->data['page']-1),$this->data['limit']);
                    $returnData['page'] = $this->data['page'];
                }
            }
            $returnData['menuList'] = $menuList;
            // dump($returnData);die;
            return json_encode($returnData);
        }else{
            return view('menu');
        }
    }


    // 侧边栏新增
    public function insert($data){
        // dump($data);die;
    	if(isset($data['name']['name_'.$this->lang]) && $data['name']['name_'.$this->lang]){
            $where['mu.lang'] = $this->lang;
            $where['mu.content'] = $data['name']['name_'.$this->lang];
            $where['zu.pid'] = isset($data['menu']) ? $data['menu'] : 0;
            $result = getSearch('menu','zu',['zu.id'],$where,[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id asc');
            if (empty($result)) {    // 验证菜单名称在当前pid下是否已存在
                $menuData['pid'] = isset($data['menu']) ? $data['menu'] : 0;
                $menuData['control'] =trim(strtolower($data['control']));
                $menuData['option'] = trim(strtolower($data['handle']));
                $menuData['is_menu'] = $data['is_menu'] == 'menu' ? 1 :0;
                $menuData['style'] = $data['style'];
                $menuData['nameclass'] = $data['nameclass'];
                $menuData['is_right'] = $data['is_right'];
                $menuData['disable'] = $data['status'] == 'true' ? 1 : 0;
                $menuData['create_at'] = time();
                $menuData['update_at'] = time();
                $menuData['drank'] = $data['sort'] !='' ? $data['sort'] :(hasData('menu',['pid'=>$menuData['pid']])+1);

                if(hasData('menu',['pid'=>$menuData['pid'],'drank'=>$menuData['drank']])){
                    $is_drank = changeDrank(1,'menu',$menuData['drank'],'',['pid'=>$menuData['pid']]);
                }
                // return $menuData;
                // 开启事务
                Db::startTrans();   
                    $res = Db::name('menu')->insertGetId($menuData);
                    if($res){

                        $administrator = getDatas('admin',['*'],['position_id'=>1]);
                        foreach ($administrator as $key => $value) {
                            Db::name('admin')->where('id',$value['id'])->update(['auth_ids'=>$value['auth_ids'].','.$res]);
                        }

                        $mkey ="menu_".$res;
                        $res = Db::name('menu')->where('id',$res)->update(['mkey'=>$mkey]);
                        $lang_cate = getLanguage();
                        foreach ($lang_cate as $k => $v) {
                            $insertData['mkey'] = $mkey;
                            $insertData['lang'] = $v['code'];
                            $insertData['content'] = $data['name']['name_'.$v['code']] == '' ? $data['name']['name_'.$this->lang] :$data['name']['name_'.$v['code']];
                            
                            $ress = Db::name('multi_lang')->insert($insertData);
                        }
                        if($ress){
                            //提交事务
                            Db::commit();
                            return  json_encode(array('status' => 1,'msg'=>lang('method').'：'.$data['name']['name_'.$this->lang].','.lang('added_successfully') ));
                        }else{
                            return  json_encode(array('status' => 0,'msg'=>lang('method').'：'.$data['name']['name_'.$this->lang].','.lang('add_failed')));
                        }
                    }else{
                        return  json_encode(array('status' => 0,'msg'=>lang('method').'：'.$data['name']['name_'.$this->lang].','.lang('add_failed') ));
                    }
            }else{
                return  json_encode(array('status' => 3,'msg'=>lang('method').'：'.$data['name']['name_'.$this->lang].','.lang('already_exists') ));
            }
    	}else{
            return  json_encode(array('status' => 2,'msg'=>lang('missing').' '.lang('method') ));
        }
        
    }


    public function addopen(){
        if(isset($this->data['request']) && $this->data['request'] == 'insert'){
            $res = $this->insert($this->data);
            return $res;
        }else if(isset($this->data['request']) && $this->data['request'] == 'add'){
            if(isset($this->data['id']) && $this->data['id']){
                // $res = getMultiLangName('menu',['*'],['id'=>$this->data['id']],'id asc');
                $res = getTree(getMultiLangName('menu',['*'],['disable'=>0,'is_menu'=>1],'id asc'));
                // dump($res);die;
                $title = lang('add_sub-functions');
                $pid = $this->data['id'];
            }else{
                $res = [];
                $title = lang('add_top_menu');
                $pid = -1;
            }
            return json_encode(array('allParent'=>$res,'title'=>$title,'requestType'=>'add','pid'=>$pid));
        }elseif(isset($this->data['request']) && $this->data['request'] == 'add_top_menu'){
            return view('menuopen',['title'=>lang('add_top_menu'),'request'=>'add_top_menu']);

        }elseif(isset($this->data['request']) && $this->data['request'] == 'add_sub-functions'){
            return view('menuopen',['title'=>lang('add_sub-functions'),'requestType'=>'add_sub-functions','pid'=>$this->data['id'],'id'=>$this->data['id']]);
        }
    }

    // 获取当前类行下 所以能用的子级
    function getChildID($table,$field,$where,$pid=0)
    {   
        $_data = Db::name($table)
                    ->field($field)
                    ->where($where)
                    ->where('pid',$pid)
                    // ->fetchSql()
                    ->select();
                // return $_data;
        if(!empty( $_data)){
            foreach ($_data as $k => $v) {
                array_push($this->getChildIDdata,$v['id']);
                $res = $this->getChildID($table,$field,$where,$v['id']);
            }
        }
        return $this->getChildIDdata;
    }

    public function editopen(){
        if(isset($this->data['request']) && $this->data['request'] == 'update'){
            unset($this->data['request']);
            // dump($this->data);die;
            if($this->data['id'] == $this->data['menu']) return json_encode(array('status'=>2,'msg'=>'所属功能选择有误，所属功能不能为自己'));

            if(!isset($this->data['name']['name_'.$this->lang]) && !$this->data['name']['name_'.$this->lang]) return json_encode(array('status'=>2,'msg'=>lang('missing_name')));
                
            $pidArr = $this->getChildID('menu',['id'],'1=1',$this->data['id']);
            if( in_array($this->data['menu'], $pidArr)) return json_encode(array('status'=>2,'msg'=>'所属功能选择有误，为当前功能的子级'));
            
            //  判断名称是否已存在
            // $hasName = hasData('multi_lang',['mkey'=>['like','%menu_%'],'lang'=>$this->lang,'content'=>$this->data['name']['name_'.$this->lang],'mkey'=>['neq','menu_'.$this->data['id']]]);
            // // dump($hasName);die;
            // if($hasName) return json_encode(array('status'=>2,'msg'=>lang('already_exists')));
            //开启事务
            Db::startTrans();   
            try{
                // 是否需要从新排序
                if(hasData('menu',['pid'=>$this->data['menu'],'drank'=>$this->data['sort']])){
                    if($this->data['sort'] != $this->data['olddrank']){
                        $is_drank = changeDrank(1,'menu',$this->data['sort'],$this->data['olddrank'],['pid'=>$this->data['menu']]);
                    }
                }
        
                unset($this->data['zh']['olddrank']);


                $updateData['pid'] = $this->data['menu'];
                $updateData['control'] = $this->data['control'];
                $updateData['option'] = $this->data['handle'];
                $updateData['is_menu'] = $this->data['is_menu'] == 'menu' ? 1 : 0;
                $updateData['style'] = $this->data['style'];
                $updateData['nameclass'] = $this->data['nameclass'];
                $updateData['disable'] = $this->data['status'] == 'true' ? 1 : 0;
                $updateData['drank'] = $this->data['sort'];
                $updateData['is_right'] = $this->data['is_right'];
                $updateData['update_at'] = time();
                $updateData['control'] = trim(strtolower($this->data['control']));
                $updateData['option'] = trim(strtolower($this->data['handle']));

                $res = updateData('menu',['id'=>$this->data['id']],$updateData);
                // return $res;
                if($res >= 0){

                    $lang_cate = getLanguage();
                    foreach ($lang_cate as $k => $v) {
                        $updateMultiData['content'] = $this->data['name']['name_'.$v['code']] == '' ? $this->data['name']['name_'.$this->lang] :$this->data['name']['name_'.$v['code']];
                        $ress = updateData('multi_lang',['mkey'=>'menu_'.$this->data['id'],'lang'=>$v['code']],$updateMultiData);
                    }

                    if($ress >= 0){
                        //提交事务
                        Db::commit();
                        return  json_encode(array('status' => 1,'msg'=>lang('proattr').$this->data['name']['name_'.$this->lang].' '.lang('edited_successfully') ));
                    }else{
                        return  json_encode(array('status' => 0,'msg'=>lang('proattr').$this->data['name']['name_'.$this->lang].' '.lang('edit_failed') ));
                    }
                }else{
                    return  json_encode(array('status' => 0,'msg'=>lang('proattr').' '.lang('edit_failed') ));
                }
            } catch (\Exception $e) {
                //回滚事务
                Db::rollback();
                return  json_encode(array('status' => 10,'msg'=>lang('edit_failed') ));
            }
        }else if(isset($this->data['request']) && $this->data['request'] == 'edit'){
            $allParent = getMultiLangName('menu',['*'],'1= 1','id asc');
            $allParent = getTree($allParent);
            foreach ($allParent as $k => $v) {
                $allParent[$k]['child'] = 1;
            }
            $info = getMultiLangName('menu',['*,drank olddrank'],['id'=>$this->data['id']],'id asc')[0];
            return json_encode(['allParent'=>$allParent,'info'=>$info,'pid'=>$this->data['pid'],'threeLevel'=>$this->data['id'],'title'=>lang('edit'),'requestType'=>'edit']);
        }else{
             
            return view('menuopen',['title'=>lang('edit'),'requestType'=>'edit','id'=>$this->data['id'],'pid'=>$this->data['pid']]);
        }
    }

    // 侧边栏状态
    public function updateStatus(){
        if($this->data['id']){
            $is_del = Db::name('menu')->where('pid',$this->data['id'])->find();
            $notic = $this->data['disable'] == 1 ? lang('locking') : lang('unlock');
            if(!$is_del){
                $res = Db::name('menu')->where('id',$this->data['id'])->update(['disable'=>$this->data['disable']]);
                if($res){
                    return json_encode(array('status' => 1,'msg'=>getValue('multi_lang',['mkey'=>'menu_'.$this->data['id'],'lang'=>$this->lang],'content').' '.$notic.' '.lang('successfully') ));
                }else{
                    return  json_encode(array('status' => 0,'msg'=>getValue('multi_lang',['mkey'=>'menu_'.$this->data['id'],'lang'=>$this->lang],'content').' '.$notic.' '.lang('failed') ));
                }
            }else{
                return  json_encode(array('status' => 0,'msg'=>getValue('multi_lang',['mkey'=>'menu_'.$this->data['id'],'lang'=>$this->lang],'content').' '.lang('already_exists').' '.$notic.' '.lang('failed')));
            }
        }else{
            return json_encode(array('status' => 2,'msg'=>lang('improve_submission_data') ));
        }
    }

     // 删除侧边栏
    public function requestDelete(){

        if($this->data['id']){
            $is_del = hasData('menu',['pid'=>$this->data['id']]);
            if(!$is_del){
                $content = getValue('multi_lang',['mkey'=>'menu_'.$this->data['id'],'lang'=>$this->lang],'content');
                $res = deleteData('menu',['id'=>$this->data['id']]);
                if($res){
                    $administrator = getDatas('admin',['*'],['position_id'=>1]);
                    foreach ($administrator as $key => $value) {
                        $auth_idArr = explode(',', $value['auth_ids']);
                        $key_ = array_search($this->data['id'],$auth_idArr);
                        if($key_){
                            unset($auth_idArr[$key_]);
                            $auth_idArr = implode(',', $auth_idArr);
                            Db::name('admin')->where('id',$value['id'])->update(['auth_ids'=>$auth_idArr]);
                        }
                    }
                    $res1 = deleteData('multi_lang',['mkey'=>'menu_'.$this->data['id']]);
                    return json_encode(array('status' => 1,'msg'=>$content.' '.lang('cleared_successfully') ));
                }else{
                    return  json_encode(array('status' => 0,'msg'=>$content.' '.lang('clear_failed') ));
                }
            }else{
                return  json_encode(array('status' => 0,'msg'=>$content.' '.lang('clear_failed') ));
            }
        }else{
            return json_encode(array('status' => 2,'msg'=>lang('improve_submission_data')));
        }
    }

}
